<template>
  <div>
    <el-dialog
      title="双随机任务"
      :visible="dialogVisible"
      custom-class="custom-dialog"
      :before-close="handleClose"
      @open="initData"
      width="78%"
      class="dialogClass"
    >
      <el-form
        ref="form"
        class="query-more-form formTop"
        size="mini"
        label-width="110px"
        :disabled="dialogType === 'detail'"
        :model="form"
        :rules="rules"
      >
        <el-row :gutter="20">
          <el-col :span="6" class="el-col"
            ><el-form-item label="任务名称" prop="taskName"
              ><el-input
                v-model="form.taskName"
                placeholder="请输入任务名称"
                maxlength="255"/></el-form-item
          ></el-col>
          <el-col :span="6" class="el-col">
            <el-form-item label="抽查数量" prop="number"
              ><el-input
                v-model="form.number"
                placeholder="请输入数量"
                maxlength="255"
            /></el-form-item>
          </el-col>
           <el-col :span="6" class="el-col">
            <el-form-item label="执法人员数" prop="zhifaNumber"
              ><el-input
                v-model="form.zhifaNumber"
                placeholder="请输入执法人员数"
                maxlength="255"
            /></el-form-item>
          </el-col>
          <el-col :span="6" class="el-col">
            <el-form-item label="巡查地点" prop="address"
              ><el-input
                v-model="form.address"
                placeholder="请输入巡查地点"
                maxlength="255"
            /></el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="6" class="el-col"
            ><el-form-item label="是否启用" class="isDelivery">
              <el-switch v-model="form.enable"></el-switch> </el-form-item
          ></el-col>
          <el-col :span="6" class="el-col">
            <el-form-item
              label="行业"
              v-if="dialogType !== 'detail'"
              prop="industry"
            >
              <!-- <el-input
                v-model="form.industryId"
                placeholder="请选择行业"
                maxlength="255"
                @focus="changeIndustryId"
              /> -->
              <el-select
                ref="industry"
                class="form_industry"
                v-model="form.industry"
                placeholder="请选择行业"
                @change="changeIndustryCode"
              >
                <el-option
                  v-for="item in industryArr"
                  :key="item.id"
                  :label="item.name"
                  :value="item.code"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="行业" v-else>
              <el-input
                v-model="form.industryName"
                placeholder="请输入行业"
                maxlength="255"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="检查主体" prop="deptName">
              <el-input
                v-model="form.deptName"
                placeholder="请选择检查主体"
                maxlength="255"
                @focus="changeDeptId"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12" class="el-col">
            <el-form-item label="检查频率" prop="frequency"
              ><el-input
                v-model="form.frequency"
                placeholder="请输入检查频率"
                maxlength="255"
            /></el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="检查时间">
              <el-date-picker
                style="width: 100%"
                v-model="form.caseTime"
                value-format="yyyy-MM-dd"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="任务要求" prop="description">
              <el-input
                v-model="form.description"
                placeholder="请输入任务要求"
                maxlength="255"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-row :gutter="20" class="addColumn">
        <el-col :span="24">
          <el-row :gutter="20">
            <el-col :span="20">
              <div class="table-title flex-start-center mb-10">
                <img :src="icon1" class="w-20 h-20 mr-5" alt="" />
                <span class="mr-5">检查对象</span>
              </div>
            </el-col>
            <el-col :span="2">
              <div
                v-if="dialogType === 'add'"
                class="operation-btn bluebg"
                @click="openSelectCheck"
              >
                添加
              </div>
            </el-col>
            <el-col :span="2">
              <div
                v-if="dialogType === 'add'"
                class="operation-btn red"
                @click="delSelectCheck"
              >
                删除
              </div>
            </el-col>
          </el-row>
          <div class="table-content">
            <el-form class="query-more-form" size="mini" label-width="60px">
            </el-form>
            <div class="">
              <div class="table-list-panel">
                <el-table
                  border
                  size="small"
                  :data="checkTableData"
                  height="300px"
                  style="width: 100%"
                  @selection-change="handleSelectionCheck"
                >
                  <el-table-column type="selection" width="50" />
                  <el-table-column
                    prop="unitName"
                    label="检查对象"
                    show-overflow-tooltip
                  />
                   <el-table-column
                    prop="legalPerson"
                    label="巡检对象法人"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    prop="businessContacts"
                    label="联系人"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    prop="businessPhone"
                    label="联系电话"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    prop="businessPremises"
                    label="经营场所"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    prop="areaCode"
                    label="区域代码"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    prop="inifiedCreditCode"
                    label="社会统一信用码"
                    show-overflow-tooltip
                  />
                  <el-table-column width="150">
                    <template slot-scope="scope">
                      <el-button
                        v-if="dialogType === 'add'"
                        class="table-inner-btn"
                        size="mini"
                        @click="delCheck(scope.row)"
                        >删除</el-button
                      >
                      <el-button
                        v-if="dialogType === 'add'"
                        class="table-inner-btn"
                        size="mini"
                        @click="openSelectMatters(scope.row)"
                        >添加</el-button
                      >
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </div>
        </el-col>
        <!-- table2 绑定对象需替换-->
        <!-- <el-col :span="12">
          <el-row :gutter="20">
            <el-col :span="14">
              <div class="table-title flex-start-center mb-10">
                <img :src="icon2" class="w-20 h-20 mr-5" alt="" />
                <span class="mr-5">检查事项</span>
              </div>
            </el-col>
            <el-col :span="5">
              <div
                v-if="dialogType === 'add'"
                class="operation-btn bluebg"
              >
                添加
              </div>
            </el-col>
            <el-col :span="5">
              <div
                v-if="dialogType === 'add'"
                class="operation-btn red"
                @click="delSelectMatters"
              >
                删除
              </div>
            </el-col>
          </el-row>
          <div class="table-content">
            <el-form class="query-more-form" size="mini" label-width="60px">
              <el-row :gutter="10"> </el-row>
            </el-form>
            <div class="">
              <div class="table-list-panel">
                <el-table
                  v-if="dialogType !== 'detail'"
                  border
                  size="small"
                  :data="tableMatterData"
                  height="300px"
                  style="width: 100%"
                  @selection-change="handleSelectionMatters"
                >
                  <el-table-column type="selection" width="50" />
                  <el-table-column
                    prop="specificBehavior"
                    label="检查事项"
                    show-overflow-tooltip
                  />
                  <el-table-column v-if="dialogType === 'add'" width="100">
                    <template slot-scope="scope">
                      <el-button
                        class="table-inner-btn"
                        size="mini"
                        @click="delMatters(scope.row)"
                        >删除</el-button
                      >
                    </template>
                  </el-table-column>
                </el-table>

                <el-table
                  v-else
                  border
                  size="small"
                  :data="tableMatterData1"
                  height="300px"
                  style="width: 100%"
                  @selection-change="handleSelectionMatters"
                >
                  <el-table-column type="selection" width="50" />
                  <el-table-column
                    prop="specificBehavior"
                    label="检查事项"
                    show-overflow-tooltip
                  />
                  <el-table-column v-if="dialogType === 'add'" width="100">
                    <template slot-scope="scope">
                      <el-button
                        class="table-inner-btn"
                        size="mini"
                        @click="delMatters(scope.row)"
                        >删除</el-button
                      >
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </div>
        </el-col> -->
      </el-row>
      <div class="footer-button">
        <el-button
          v-if="dialogType === 'add'"
          size="mini"
          class="submit-btn"
          @click="addPatrol"
          >生成对象</el-button
        >
      </div>
    </el-dialog>
    <SelectCheckObjectDialog
      :dialog-check-visible="selectCheckVisible"
      :selected-check="checkTableData"
      @closeCheckDialog="closeCheckDialog"
      @addCheck="addCheck"
    />
    <SelectMattersDialog
      :dialog-matters-visible="dialogMattersVisible"
      :selected-matters="tableMatterData"
      :pid="form.itemTypeId"
      @closeMattersDialog="dialogMattersVisible = false"
      @addMatters="addMatters"
      :caseCodeList="caseCodeList"
      :inspectObject="inspectObject"
      @inspectObj="inspectObj"
    />

    <!-- 检查主体弹窗 -->
    <IndustryIdDialog
      :dialogVisible="ThreeTypeDialogVisible"
      @closeDialog="ThreeTypeDialogVisible = false"
      @inspectData="inspectData"
    />
  </div>
</template>

<script>
import Pagination from "@/components/Pagination";
import IndustryIdDialog from "./industryIdDialog";
import icon1 from "@/assets/images/icon/icon1.png";
import icon2 from "@/assets/images/icon/icon2.png";
import SelectCheckObjectDialog from "./SelectCheckObjectDialog";
import SelectMattersDialog from "./SelectMattersDialog";
import {
  queryRandomUser,
  queryRandomObj,
  getPatrolUser
} from "@/api/system/dept";
import { addPatrolPlan } from "@/api/system/inspectionItemRecord";
import { getList } from "@/api/system/matters";
import { sourceType, industryArea } from "@/api/case";

export default {
  components: {
    Pagination,
    SelectCheckObjectDialog,
    SelectMattersDialog,
    IndustryIdDialog
  },
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    },
    type: {
      type: Number,
      default: 0
    },
    dialogType: {
      type: String,
      default: "detail"
    },
    obj: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      rules: {
        taskName: [
          { required: true, message: "请输入任务名称", trigger: "blur" }
        ],
        number: [
          { required: true, message: "请输入抽查数量", trigger: "blur" }
        ],
        zhifaNumber: [
          { required: true, message: "请输入执法人员数", trigger: "blur" }
        ],
        address: [
          { required: true, message: "请输入巡查地址", trigger: "blur" }
        ],
        industry: [
          { required: true, message: "请选择行业", trigger: "change" }
        ],
        caseTime: [
          {
            type: "date",
            required: true,
            message: "请选择时间",
            trigger: "change"
          }
        ],
        frequency: [
          { required: true, message: "请输入检查频率", trigger: "blur" }
        ],
        deptName: [
          { required: true, message: "请选择检查主体", trigger: "change" }
        ],
        description: [
          { required: true, message: "请输入任务要求", trigger: "blur" }
        ]
      },
      icon1,
      icon2,
      // 部门级联选择器
      deptOptions: [],
      changePatrolUserIdArr: [],
      inspectObjArr: [],
      deptProps: {
        value: "id",
        lable: "lable"
      },
      inspectObject: {},
      caseCode: "",
      caseCodeList: [],
      // 行业类型
      industryArr: [],
      // 检查对象表格数据
      checkTableData: [],
      selectCheckVisible: false,
      ThreeTypeDialogVisible: false,
      // 要删除的检查对象数据
      delCheckTableData: [],
      // 检查事项表格数据
      tableMatterData: [],
      tableMatterData1: [],
      dialogMattersVisible: false,
      // 要删除的检查事项数据
      delTableMatterData: [],
      query: {
        total: 0,
        pageNum: 1,
        pageSize: 10
      },
      // 表单
      form: {
        deptId: "",
        type: 2,
        status: 0,
        number: 1,
        caseTime: [],
        beginTime: "",
        endTime: "",
        frequency: 1
      },
      enforcementMan: ""
    };
  },

  watch: {
    obj(val) {
      if (this.dialogType === "detail") {
        this.checkTableData = val.unitInfoList;
        val.categoryList.forEach(item => {
          item.specificBehavior = item.categoryCompleteName;
        });
        this.tableMatterData1 = val.categoryList;
      }
    }
  },

  methods: {
    getIsData() {
      if (!this.form.deptName) {
        this.$message.warning("请选择检查主体");
      }
    },

    changePatrolUserId() {
      this.enforcementMan = val.join(",");
    },

    inspectObj(val) {
      this.inspectObjArr.push(val);
    },

    // 主体部门
    inspectData(data) {
      this.form.deptId = data.id;
      this.form.deptName = data.label;
      this.query.deptId = data.id;
      getPatrolUser(this.query)
        .then(res => {
          let { code, rows } = res;
          if (code == 200) {
            rows.forEach(item => {
              this.changePatrolUserIdArr.push({
                name: item.nickName,
                id: item.id
              });
            });
          }
        })
        .catch(() => {});
    },

    changeDeptId() {
      this.ThreeTypeDialogVisible = true;
    },

    // 查询行业
    changeIndustryId() {
      sourceType({
        parentCode: 0,
        typeCode: 2
      }).then(result => {
        let { code, rows } = result;
        if (code == 200) {
          this.industryArr = rows;
        }
      });
    },

    // 选择行业
    changeIndustryCode(val) {
      this.caseCode = val;
      sessionStorage.setItem("case_Code", val);
      // this.$bus.emit("case_Code");
      industryArea({ parentCode: val })
        .then(result => {
          let { rows, code } = result;
          if (code == 200) {
            this.caseCodeList = rows;
          }
        })
        .catch({});

      this.industryArr.forEach(item => {
        if (val == item.code) {
          this.form.primaryCategoryName = item.name;
          this.form.primaryCategoryId = item.id;
        }
      });
    },
    handleClose() {
      this.clearData();
      this.$emit("closeDialog");
    },
    initData() {
      // this.getIndustry();
      // this.getDept();
      this.changeIndustryId();
      this.form.type = this.type;
      if (this.obj && this.obj.id) {
        this.form = this.obj;
        this.form.itemTypeId = parseInt(this.form.itemTypeId);
        const timeObj = {
          caseTime: [this.obj.startTime, this.obj.endTime]
        };
        this.form = Object.assign(this.form, timeObj);
        this.tableMatterData = this.form.checklistResponsibilities;
        if (this.form.patrolGroups)
          this.checkTableData = this.form.patrolGroups[0].unitList;
      }
    },
    // 打开选择检查对象对话框
    openSelectCheck() {
      if (!this.form.deptName) {
        this.$message.warning("请选择检查主体");
      } else if (!this.form.number) {
        this.$message.warning("请输入抽查数量");
      } else if (!this.form.zhifaNumber) {
        this.$message.warning("请输入执法人员数量");
      } else {
        queryRandomObj({
          number: this.form.number,
          keyId: this.form.deptId
        }).then(res => {
          let { rows, code } = res;
          if (code == 200) {
            this.checkTableData = rows;
          }
        });

        queryRandomUser({
          number: this.form.zhifaNumber,
          keyId: this.form.deptId
        }).then(res => {
          let { rows, code } = res;
          if (code == 200) {
            this.enforcementMan = rows.map(item => item.id).join(",");
          }
        });
      }
    },
    // 检查对象多选
    handleSelectionCheck(val) {
      this.delCheckTableData = val;
    },
    // 检查事项多项
    handleSelectionMatters(val) {
      this.delTableMatterData = val;
    },
    // 批量删除检查对象
    delSelectCheck() {
      this.delCheckTableData.forEach(item => {
        this.delCheck(item);
      });
    },
    // 批量删除检查事项
    delSelectMatters() {
      this.delTableMatterData.forEach(item => {
        this.delMatters(item);
      });
    },
    // 关闭选择检查对象对话框
    closeCheckDialog() {
      this.selectCheckVisible = false;
    },
    // 添加检查对象
    addCheck(data) {
      if (data instanceof Array) {
        data.forEach(item => {
          this.checkTableData.push({
            id: item.id,
            unitName: item.unitName,
            unitLegalPerson: item.legalPerson,
            unitInfoCode: item.inifiedCreditCode,
            unitBusinessContacts: item.businessContacts,
            unitBusinessPhone: item.businessPhone,
            unitInfoAddress: item.unitInfoAreaCode,
            unitInfoAreaCode: item.areaCode
          });
        });
      } else {
        this.checkTableData.push({
          id: data.id,
          unitName: data.unitName,
          unitLegalPerson: data.legalPerson,
          unitInfoCode: data.inifiedCreditCode,
          unitBusinessContacts: data.businessContacts,
          unitBusinessPhone: data.businessPhone,
          unitInfoAddress: data.businessPremises,
          unitInfoAreaCode: data.areaCode
        });
      }
    },
    // 删除检查对象
    delCheck(row) {
      this.checkTableData.splice(this.checkTableData.indexOf(row), 1);
    },

    // 打开选择检查事项对话框
    openSelectMatters(row) {
      if (this.caseCode == "") {
        this.$message.warning("请选择行业");
      } else {
        this.dialogMattersVisible = true;
      }
      this.inspectObject = row;
    },

    // 添加检查事项
    addMatters(data, pid) {
      this.form.itemTypeId = pid;
      if (data instanceof Array) {
        data.forEach(item => {
          const { code, categoryCompleteName } = item;
          this.tableMatterData.push({
            id: code,
            specificBehavior: categoryCompleteName
          });
        });
      } else {
        const { code, categoryCompleteName } = data;
        this.tableMatterData.push({
          id: code,
          specificBehavior: categoryCompleteName
        });
      }
    },
    // 删除检查事项
    delMatters(row) {
      this.tableMatterData.splice(this.tableMatterData.indexOf(row), 1);
      if (this.tableMatterData.length === 0) {
        this.form.itemTypeId = null;
      }
    },
    // 添加巡检记录
    addPatrol() {
      this.$refs["form"].validate(valid => {
        if (!this.form.caseTime.length) {
          this.$message.warning("请选择检查时间");
        } else if (!this.checkTableData.length) {
          this.$message.warning("请添加检查对象");
        } else if (valid) {
          // 时间
          this.form.beginTime = new Date(this.form.caseTime[0]).getTime();
          this.form.endTime = new Date(this.form.caseTime[1]).getTime();

          this.form.frequencyCompany = 4;

          this.form.enable = this.form.enable ? 0 : 1;

          this.form.units = this.inspectObjArr;

          this.form.patrolUserId = this.enforcementMan;

          addPatrolPlan(this.form)
            .then(res => {
              this.$message.success("任务分配成功");
              this.handleClose();
              this.$emit("refreshData");
            })
            .catch(() => {
              this.$message.error("任务分配失败。");
            });
        }
      });
    },
    // 清空表单
    clearData() {
      this.form = {
        deptId: "",
        name: "",
        type: 1,
        content: "",
        checkCount: 0,
        caseTime: [],
        startTime: "",
        endTime: "",
        industryId: "",
        industryName: "",
        itemTypeId: null,
        itemTypeName: "",
        name: "",
        responsibilityIds: [],
        userUnits: []
      };
      this.checkTableData = [];
      this.tableMatterData = [];
    }
  }
};
</script>

<style lang="scss" scoped>
.form_industry {
  /deep/ .el-input__inner {
    width: 240px;
  }
}
.isDelivery {
  /deep/ .el-form-item__label {
    border-right: 1px solid #dbdcde;
  }
  .el-switch {
    margin-left: 10px;
    margin-top: 8px;
  }
}
.table-title {
  color: #1189ef;
  font-weight: bold;
}
.footer-button {
  margin-top: 20px;
  text-align: center;
}
.operation-btn {
  padding: 0px;
  text-align: center;
  width: 70px;
  height: 28px;
  line-height: 28px;
  position: relative;
  bottom: 5px;
}
.el-col {
  margin-bottom: 0px;
}
.formTop div {
  margin-bottom: 2px;
}
.addColumn {
  margin-top: 25px;
}
.dialogClass .el-dialog_body {
  padding-top: 0px !important;
}
.el-dialog_body {
  padding-top: 0px !important;
}
</style>
